package com.magicode.screen.base;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
//import android.support.multidex.MultiDex;
import android.support.v4.app.ActivityCompat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.widget.Toast;

import com.BV.LinearGradient.LinearGradientPackage;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.github.wuxudong.rncharts.MPAndroidChartPackage;
import com.magicode.screen.AppConfig;
import com.facebook.soloader.SoLoader;
import com.magicode.screen.BuildConfig;
import com.magicode.screen.autoheightwebview.AutoHeightWebViewPackage;
import com.magicode.screen.imagepicker.PickerPackage;
import com.magicode.screen.react.packages.MgcReactPackage;
import com.magicode.screen.util.StringUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;


import java.io.File;
import java.util.Arrays;
import java.util.List;

import fr.greweb.reactnativeviewshot.RNViewShotPackage;


@SuppressLint("InflateParams")
public class BaseApplication extends Application implements ReactApplication {

    private static String PREF_NAME = "creativelocker.pref";
    private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
    static Context _context;
    static Resources _resource;
    private static String lastToast = "";
    private static long lastToastTime;

    private static boolean sIsAtLeastGB;
	//    图片缓存地址
	protected static File imageCacheDir = null;
	// Storage Permissions variables
	private static final int REQUEST_EXTERNAL_STORAGE = 1;
	private static String[] PERMISSIONS_STORAGE = {
			android.Manifest.permission.READ_EXTERNAL_STORAGE,
			android.Manifest.permission.WRITE_EXTERNAL_STORAGE
	};

    static {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
	    sIsAtLeastGB = true;
	}
    }

    @Override
    public void onCreate() {
	super.onCreate();
	_context = getApplicationContext();
	_resource = _context.getResources();
//	ImageLoader初始化
//    ImageLoaderConfiguration configuration = ImageLoaderConfiguration  
//            .createDefault(this);
	initImageLoader(_context);
	
    SoLoader.init(this, /* native exopackage */ false);
    }

	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you may tune some of them,
		// or you can create default configuration by
		//  ImageLoaderConfiguration.createDefault(this);
		// method.
		initImageCacheDisk(context);
		ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
		config.threadPriority(Thread.NORM_PRIORITY - 2);
		config.denyCacheImageMultipleSizesInMemory();
		config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
		config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
		config.tasksProcessingOrder(QueueProcessingType.LIFO);
		config.writeDebugLogs(); // Remove for release app
		config.diskCache(new UnlimitedDiskCache(imageCacheDir));
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config.build());
	}
    public static synchronized BaseApplication context() {
	return (BaseApplication) _context;
    }

    public static Resources resources() {
	return _resource;
    }

    /**
     * 放入已读文章列表中
     * 
     * @param prefFileName
	 * @param key
	 * @param value
     */
    public static void putReadedPostList(String prefFileName, String key,
	    String value) {
	SharedPreferences preferences = getPreferences(prefFileName);
	int size = preferences.getAll().size();
	Editor editor = preferences.edit();
	if (size >= 100) {
	    editor.clear();
	}
	editor.putString(key, value);
	apply(editor);
    }
    
    /**
     * 读取是否是已读的文章列表
     * 
     * @param prefFileName
	 * @param key
     * @return
     */
    public static boolean isOnReadedPostList(String prefFileName, String key) {
	return getPreferences(prefFileName).contains(key);
    }
    
    /***
     * 记录列表上次刷新时间
     * @author 火蚁
     * 2015-2-9 下午2:21:37
     *
     * @return void
     * @param key
     * @param value
     */
    public static void putToLastRefreshTime(String key, String value) {
	SharedPreferences preferences = getPreferences(LAST_REFRESH_TIME);
	Editor editor = preferences.edit();
	editor.putString(key, value);
	apply(editor);
    }
    
    /***
     * 获取列表的上次刷新时间
     * @author 火蚁
     * 2015-2-9 下午2:22:04
     *
     * @return String
     * @param key
     * @return
     */
    public static String getLastRefreshTime(String key) {
	return getPreferences(LAST_REFRESH_TIME).getString(key, StringUtils.getCurTimeStr());
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void apply(Editor editor) {
	if (sIsAtLeastGB) {
	    editor.apply();
	} else {
	    editor.commit();
	}
    }

    public static void set(String key, boolean value) {
	Editor editor = getPreferences().edit();
	editor.putBoolean(key, value);
	apply(editor);
    }

    public static void set(String key, String value) {
	Editor editor = getPreferences().edit();
	editor.putString(key, value);
	apply(editor);
    }

    public static boolean get(String key, boolean defValue) {
	return getPreferences().getBoolean(key, defValue);
    }

    public static String get(String key, String defValue) {
	return getPreferences().getString(key, defValue);
    }

    public static int get(String key, int defValue) {
	return getPreferences().getInt(key, defValue);
    }

    public static long get(String key, long defValue) {
	return getPreferences().getLong(key, defValue);
    }

    public static float get(String key, float defValue) {
	return getPreferences().getFloat(key, defValue);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static SharedPreferences getPreferences() {
	SharedPreferences pre = context().getSharedPreferences(PREF_NAME,
		Context.MODE_MULTI_PROCESS);
	return pre;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static SharedPreferences getPreferences(String prefName) {
	return context().getSharedPreferences(prefName,
		Context.MODE_MULTI_PROCESS);
    }

    public static int[] getDisplaySize() {
	return new int[] { getPreferences().getInt("screen_width", 480),
		getPreferences().getInt("screen_height", 854) };
    }

    public static void saveDisplaySize(Activity activity) {
	DisplayMetrics displaymetrics = new DisplayMetrics();
	activity.getWindowManager().getDefaultDisplay()
		.getMetrics(displaymetrics);
	Editor editor = getPreferences().edit();
	editor.putInt("screen_width", displaymetrics.widthPixels);
	editor.putInt("screen_height", displaymetrics.heightPixels);
	editor.putFloat("density", displaymetrics.density);
	editor.commit();
    }

    public static String string(int id) {
	return _resource.getString(id);
    }

    public static String string(int id, Object... args) {
	return _resource.getString(id, args);
    }

    public static void showToast(int message) {
	showToast(message, Toast.LENGTH_LONG, 0);
    }

    public static void showToast(String message) {
	showToast(message, Toast.LENGTH_LONG, 0, Gravity.BOTTOM);
    }

    public static void showToast(int message, int icon) {
	showToast(message, Toast.LENGTH_LONG, icon);
    }

    public static void showToast(String message, int icon) {
	showToast(message, Toast.LENGTH_LONG, icon, Gravity.BOTTOM);
    }

    public static void showToastShort(int message) {
	showToast(message, Toast.LENGTH_SHORT, 0);
    }

    public static void showToastShort(String message) {
	showToast(message, Toast.LENGTH_SHORT, 0, Gravity.BOTTOM);
    }

    public static void showToastShort(int message, Object... args) {
	showToast(message, Toast.LENGTH_SHORT, 0, Gravity.BOTTOM, args);
    }

    public static void showToast(int message, int duration, int icon) {
	showToast(message, duration, icon, Gravity.BOTTOM);
    }

    public static void showToast(int message, int duration, int icon,
	    int gravity) {
	showToast(context().getString(message), duration, icon, gravity);
    }

    public static void showToast(int message, int duration, int icon,
	    int gravity, Object... args) {
	showToast(context().getString(message, args), duration, icon, gravity);
    }

    public static void showToast(String message, int duration, int icon,
	    int gravity) {
	if (message != null && !message.equalsIgnoreCase("")) {
	    long time = System.currentTimeMillis();
	    if (!message.equalsIgnoreCase(lastToast)
		    || Math.abs(time - lastToastTime) > 2000) {
//		View view = LayoutInflater.from(context()).inflate(
//			R.layout.view_toast, null);
//		((TextView) view.findViewById(R.id.title_tv)).setText(message);
//		if (icon != 0) {
//		    ((ImageView) view.findViewById(R.id.icon_iv))
//			    .setImageResource(icon);
//		    ((ImageView) view.findViewById(R.id.icon_iv))
//			    .setVisibility(View.VISIBLE);
//		}
		Toast toast = new Toast(context());
//		toast.setView(view);
		if (gravity == Gravity.CENTER) {
		    toast.setGravity(gravity, 0, 0);
		} else {
		    toast.setGravity(gravity, 0, 35);
		}

		toast.setDuration(duration);
		toast.show();
		lastToast = message;
		lastToastTime = System.currentTimeMillis();
	    }
	}
    }
	private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
		@Override
		public boolean getUseDeveloperSupport() {
			return BuildConfig.DEBUG;

		}

		@Override
		protected List<ReactPackage> getPackages() {
			return Arrays.<ReactPackage>asList(
					new MainReactPackage(),new MgcReactPackage(), new MPAndroidChartPackage()
					, new PickerPackage(),new RNViewShotPackage(),new AutoHeightWebViewPackage()
					,new LinearGradientPackage(),new RNFetchBlobPackage()
					/* Add package */
			);
		}
	};

	@Override
	public ReactNativeHost getReactNativeHost() {
		return mReactNativeHost;
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
//		MultiDex.install(this);
	}

	//persmission method.
	@TargetApi(Build.VERSION_CODES.M)
	public static void verifyPermissions(Activity activity) {
		// Check if we have read or write permission
		int writePermission = ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
		int readPermission = ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.READ_EXTERNAL_STORAGE);

		if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
			// We don't have permission so prompt the user
			ActivityCompat.requestPermissions(
					activity,
					PERMISSIONS_STORAGE,
					REQUEST_EXTERNAL_STORAGE
			);
		}
		if (!Settings.canDrawOverlays(activity)) {
			Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			activity.startActivityForResult(intent, 1);
		}
	}
	public static boolean shouldAskPermission(){
		return(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1);
	}

	/**
	 //     * 初始化图片缓存地址
	 * @param context
	 */
	protected static void initImageCacheDisk(Context context){

		if(imageCacheDir == null){
			imageCacheDir = new File(Environment
					.getExternalStorageDirectory()+
					AppConfig.EXTERNAL_PICTURES_PATH);
		}
	}
}
